

package cn.liyao.web.controller;

import cn.liyao.tool.annotation.RequireToken;
import cn.liyao.tool.api.R;
import cn.liyao.web.constant.MessageTypeU;
import cn.liyao.web.holder.CurrentUserIdHolder;
import cn.liyao.web.model.FriendRecord;
import cn.liyao.web.model.OfflineMessages;
import cn.liyao.web.repository.FriendRecordRepository;
import cn.liyao.web.repository.OfflineMessageRepository;
import cn.liyao.web.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transactional;
import java.util.List;

@RestController

public class FriendRecordController {

    private final FriendRecordRepository friendRecordRepository;

    private final UserRepository userRepository;

    private final OfflineMessageRepository offlineMessageRepository;


    @Autowired
    public FriendRecordController(FriendRecordRepository friendRecordRepository, UserRepository userRepository, OfflineMessageRepository offlineMessageRepository) {
        this.friendRecordRepository = friendRecordRepository;
        this.userRepository = userRepository;

        this.offlineMessageRepository = offlineMessageRepository;
    }


    @GetMapping("/friend/record/list")
    @RequireToken()
    @CrossOrigin
    @Transactional
    public R friendList() {
        String userId = CurrentUserIdHolder.getCurrentUser();
        List<FriendRecord> friendRecordList = friendRecordRepository.findAllBySenderIdOrReceiveIdOrderByCreateAtDesc(userId, userId);
        for (FriendRecord item : friendRecordList) {
            if(!item.getSenderId().equals(userId)){
                item.setUser(userRepository.findById(item.getSenderId()).get());
            }else if(!item.getReceiveId().equals(userId)){
                item.setUser(userRepository.findById(item.getReceiveId()).get());
            }
        }

        offlineMessageRepository.deleteAllByToAndTypeu(userId,MessageTypeU.AddFriend.getValue());

        return R.data(friendRecordList);


    }

}